#include "grayscalequantizer.h"

WingGif::GrayscaleQuantizer::GrayscaleQuantizer(QColor transparent,
                                                int maxColors)
    : PaletteQuantizer(QVector<QColor>()) {
  colors.clear();

  auto _maxColorsWithTransparency =
      transparent.isValid() ? maxColors - 1 : maxColors;

  setMaxColorsWithTransparency(_maxColorsWithTransparency);

  // Initialize a new color table with entries that are determined by some
  // optimal palette-finding algorithm.
  for (auto i = 0; i < _maxColorsWithTransparency; i++) {
    // Even distribution of grayscale colors.
    auto intensity = uint32_t(i * 0xFF / (_maxColorsWithTransparency - 1));

    colors.append(QColor::fromRgba(
        qRgba(int(intensity), int(intensity), int(intensity), 0xFF)));
  }

  if (transparent.isValid())
    colors.append(transparent);
}

uchar WingGif::GrayscaleQuantizer::quantizePixel(QColor pixel) {
  auto luminance =
      pixel.red() * 0.299 + pixel.green() * 0.587 + pixel.blue() * 0.114;

  // Gray scale is an intensity map from black to white.
  // Compute the index to the grayscale entry that approximates the luminance,
  // and then round the index. Also, constrain the index choices by the number
  // of colors to do, and then set that pixel's index to the byte value.

  // return (byte)((int)((luminance + 0.5) * Colors.Length) >> 8); //Without
  // transparency. return (byte)(luminance + 0.5); //Without configurable color
  // count.

  return uchar((int)((luminance + 0.5) * maxColorsWithTransparency()) >>
               8); // Returns the color index.
}
